<?php

/**
 * Consul 服务注册发现删除 
 */
namespace App\Consul;
use Hyperf\Consul\Agent;
use Hyperf\Consul\Health;
use Psr\Container\ContainerInterface;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Consul\KV;

class ConsulServices
{
    private $container;
    public $consul_url;

    // 服务
    public $servers;

    /**
     * ConsulServices constructor.
     * @param $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    // 服务注册
    public function registerService (array $service)
    {
        $agent = new Agent(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                'base_uri' => $this->consul_url,
            ]);
        });
        return $agent->registerService($service);
    }

    // 服务发现
    public function getService (string $serviceName)
    {
        $health = new Health(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                'base_uri' => $this->consul_url,
            ]);
        });
        $resp = $health->service($serviceName);
        $servers = $resp->json();
        if (empty($servers)){
            $this->servers[$serviceName] = [];
        }
        // 心跳机制
        $this->servers[$serviceName] = [];
        foreach ($servers as $server) {
            $this->servers[$serviceName][] = $server;
        }
    }

    // 删除服务
    public function delService (string $serviceId)
    {
        $agent = new Agent(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                'base_uri' => $this->consul_url,
            ]);
        });
        return $agent->deregisterService($serviceId);
    }
    
    //del Kv
    public function delKv (string $key)
    {
        $agent = new KV(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                'base_uri' => $this->consul_url,
            ]);
        });
        return $agent->delete($key);
    }
    
    //put Kv
    public function putKv (string $key ,$value )
    {
        $agent = new KV(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                'base_uri' => $this->consul_url,
            ]);
        });
        return $agent->put($key,$value);
    }
}